<script lang="ts" setup>
import { ref, reactive, type Ref, onMounted } from "vue";
import UniPopup from "@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue";
import UniForms from "@/uni_modules/uni-forms/components/uni-forms/uni-forms.vue";
import UniFormsItem from "@/uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue";
import UniEasyinput from "@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue";
import UniDataSelect from "@/uni_modules/uni-data-select/components/uni-data-select/uni-data-select.vue";
import BbmSelect from "@/components/bbm-select.vue";
import { getActiveDeVo, type ActiveDeWxVo, registerActive, type ActiveForm } from "@/api/active";
import {baseUrl} from "@/api/http"
import UniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import { onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";
const signupPopup = ref();

const formData = reactive({

});



interface timeContent {
	time: string,
	content: string
}


const activeVo: Ref<ActiveDeWxVo> = ref({
	id: 0,
	activeTitle: "",
	activeBegin: "",
	activeEnd: "",
	bannerList: [],
	activeAddr: "",
	activeLabel: "",
	activePrice: 0,
	activeOriginPrice: 0,
	activeInstance: [],
	activeAim: "",
	activeTrip: "",
	activeTargetGroup: "",
	guests: [],
	activeRegisterDeadline: "",
	activeLimit: 0,
	activeRegisteredNum: 0,
	activeForm: []
})



const activeLabel: Ref<string[]> = ref([]);
const activeTrip: Ref<timeContent[]> = ref([]);


const handleBack = () => {
  uni.navigateBack();
};



const handleShare = () => {
  uni.showShareMenu({
    withShareTicket: true,
    menus: ["shareAppMessage", "shareTimeline"],
  });
};

//因没钱废弃查询地图接口
// const handleLocation = () => {
//   uni.openLocation({
//     latitude: 31.2304,
//     longitude: 121.5075,
//     name: "上海市浦东新区世纪大道1号",
//     address: "上海市浦东新区世纪大道1号",
//   });
// };

const handleSignup = () => {
  signupPopup.value.open();
};
const closePopup = () => {
  signupPopup.value.close();
};
const submitForm = () => {

  console.log(formData)

  // 验证必填字段
  const requiredFields = activeVo.value.activeForm
  const missingFields = requiredFields.filter(item => {
	//@ts-ignore
    const value = formData[item.name]
    return !value || (Array.isArray(value) && value.length === 0) || value=== ""
  })

  if (missingFields.length > 0) {
    uni.showToast({
      title: `请填写${missingFields.map(f => f.label).join("、")}`,
      icon: "none",
      duration: 2000
    })
    return
  }

  // 检查多选字段是否至少选择一项
  const multiSelectField = activeVo.value.activeForm.find(item => item.inputType === "2")
  //@ts-ignore
  if (multiSelectField && formData[multiSelectField.name]?.length === 0) {
    uni.showToast({
      title: `请至少选择一项${multiSelectField.label}`,
      icon: "none",
      duration: 2000
    })
    return
  }
  
  console.log(formData)

  
  const data:ActiveForm = {
	  id: 0,
	  activeId: activeVo.value.id,
	  value: JSON.stringify(formData),
	  tableId: 0
  }
  
  registerActive(data).then(res => {
	  if(res.data.data.success){
		  uni.showToast({
		    title: "报名成功",
		    icon: "success",
		  })
	  }else{
		 uni.showToast({
		   title: res.data.data.msg,
		   icon: "error",
		 }) 
	  }
	  // 所有验证通过后提交
	  
  })
  
  

  closePopup()

  // 清空表单数据（可选）
  Object.keys(formData).forEach(key => {
	//@ts-ignore
    formData[key] = Array.isArray(formData[key]) ? [] : ""
  })
};


const init = async () => {

  let id = await uni.getStorage({
	  key: "activeId",
  })
	
  let data = await getActiveDeVo(id.data);
  

  activeVo.value = data.data.data.data
  
  //初始化实例数据
  activeVo.value.activeInstance.forEach(i => {
	  if (i.fileType === "m4v" || i.fileType === "mp4" || i.fileType === "avI" || i.fileType === "wmf" || i.fileType === "ASF" || i.fileType === "webm") {
		  i.isVideo = true
	  } else {
		  i.isVideo = false
	  }
  })
	
  // 初始化标签数据
  activeLabel.value = activeVo.value.activeLabel.split(",") || []

  //初始化行程
  activeTrip.value = JSON.parse(activeVo.value.activeTrip)
  
  

  // 初始化表单数据
  activeVo.value.activeForm.forEach(item => {
	  //@ts-ignore
	  formData[item.tableColumnName] = item.inputType === "2" ? [] : ""
	  
	  if (item.inputType === "2" || item.inputType === "1") {
		  item.optionValue = item.optionValue.split(",")
	  }
	  
	  if (item.inputType === "1") {
		  //@ts-ignore
		  let data:any[] = []
		  
		  item.optionValue.forEach((i: any) => {
			  data.push({
				  text: i,
				  value: i
			  })
		  })
		  
		  item.optionValue = data
		  
	  }
	  
	  
  })
	
}

onShareAppMessage(() => ({
    title: '如初国风馆',
    path: '/pages/index/index', // 替换为你的页面路径
    imageUrl: 'https://only114514.oss-cn-hangzhou.aliyuncs.com/ruchu/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250606204232.jpg' // 可选：分享图片
  }));
  // 分享到朋友圈
  onShareTimeline(() => ({
	  title: '如初国风馆',
	  path: '/pages/index/index', // 替换为你的页面路径
	  imageUrl: 'https://only114514.oss-cn-hangzhou.aliyuncs.com/ruchu/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250606204232.jpg' // 可选：分享图片
  }));

const playVideo = () => {
	console.log("开始播放")
}

const pre = (url:string) => {
	uni.previewImage({
		urls: [url]
	})
}
init()


</script>

<template>
  <view class="page">
    <!-- 顶部主视觉区 -->
    <view class="header">
      <swiper class="swiper" circular autoplay interval="3000" duration="500">
        <swiper-item v-for="(item, index) in activeVo.bannerList" :key="index">
          <image
            v-if="!item.isVideo"
            class="cover-image"
            :src="baseUrl + item.url"
            mode="aspectFill"
			@click="pre(baseUrl + item.url)"
          />
          <video
            v-else
            class="cover-video"
            :src="item.url"
            autoplay
            loop
            muted
            :show-play-btn="false"
            :controls="false"
            object-fit="cover"
			play-strategy
          ></video>
        </swiper-item>
      </swiper>
      <view class="header-overlay">
        <view class="header-content">
          <view class="header-actions">
            <uni-icons
              class="cursor-pointer"
              type="back"
              size="24"
              color="#FFFFFF"
              @click="handleBack"
            />
            <uni-icons
              class="cursor-pointer"
              type="share"
              size="24"
              color="#FFFFFF"
              @click="handleShare"
            />
          </view>
          <text class="event-title">{{activeVo.activeTitle}}</text>
        </view>
      </view>
    </view>
    <!-- 滚动内容区 -->
    <scroll-view scroll-y class="content">
		
      <!-- 基础信息卡片 -->
      <view class="info-card">
        <view class="info-item">
          <uni-icons type="calendar" size="20" color="#666666" />
          <text class="info-text">{{activeVo.activeBegin}} 至 {{activeVo.activeEnd}}</text>
        </view>
        <view class="info-item cursor-pointer" >
          <uni-icons type="location" size="20" color="#666666" />
          <text class="info-text">{{activeVo.activeAddr}}</text>
        </view>
        <view class="info-item">
          <uni-icons type="info" size="20" color="#666666" />
          <view class="tag-container" v-for="i in activeLabel">
            <text class="tag">{{i}}</text>
          </view>
        </view>
        <view class="info-item">
          <uni-icons type="wallet" size="20" color="#666666" />
          <text class="price">¥{{activeVo.activePrice}}</text>
          <text class="price-original">原价 ¥{{activeVo.activeOriginPrice}}</text>
        </view>
      </view>
	  
      <!-- 活动详情 -->
      <view class="section">
        <view class="section-title">活动详情</view>
        <view class="detail-content">
			
		  <text class="detail-subtitle">活动实例</text>
		  
		  <swiper class="detail_video_img">
			  <swiper-item v-for="i in activeVo.activeInstance" class="video_img-itme">
				  <video 
					class="detail_video" 
					show-loading
					autopla
					@play="playVideo"
					v-if="i.isVideo" 
					:src="baseUrl + i.url"></video>
				  <image class="detail_img" v-else :src="baseUrl + i.url"
					@click="pre(baseUrl + i.url)"
				  ></image>
			  </swiper-item>
		  </swiper>
			
          <text class="detail-subtitle">活动介绍</text>
          <text class="detail-text"
            >{{activeVo.activeAim}}</text
          >
          <!-- <text class="detail-subtitle">活动流程</text>
          <view class="timeline">
			  
            <view class="timeline-item" v-for="i in activeTrip">
              <text class="time">{{ i.time }}</text>
              <text class="event">{{ i.content }}</text>
            </view>
			
          </view> -->
        </view>
      </view>
      <!-- 参与人员信息 -->
      <view class="section">
        <!-- <view class="section-title">参与人员</view> -->
        <view class="people-info">
          <!-- <view class="organizer">
            <image
              class="avatar"
              src="https://tse1-mm.cn.bing.net/th/id/OIP-C.7Ku3H7-2L9P2r_QvMA9OvgHaE6?w=292&h=194&c=7&r=0&o=5&dpr=1.3&pid=1.7"
              mode="aspectFill"
            />
            <text class="name">如初汉服</text>
            <text class="role">主办方代表</text>
          </view> -->
          <view class="audience">
            <text class="subtitle">目标受众</text>
            <text class="text">{{activeVo.activeTargetGroup}}</text>
          </view>
          <!-- <view class="guests">
            <text class="subtitle">特邀嘉宾</text>
            <view class="avatar-list">
				<view 
					v-for="(guest, index) in activeVo.guests"
					:key="index"
					style="display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					font-size: 18rpx;
					font-weight: 700;
					line-height: 3;
					"
				>
					<image
					  class="guest-avatar"
					  :src="baseUrl + guest.avatar"
					  mode="aspectFill"
					/>
					<text>{{guest.name}}</text>
				</view>
            </view>
          </view> -->
        </view>
      </view>
      <!-- 报名信息 -->
      <view class="section">
        <view class="section-title">报名信息</view>
        <view class="signup-info">
          <view class="info-row">
            <text class="label">报名截止</text>
            <text class="value">{{activeVo.activeRegisterDeadline}}</text>
          </view>
          <view class="info-row">
            <text class="label">人数限制</text>
            <view class="progress-container">
              <view class="progress-bar">
                <view
                  class="progress"
                  :style="{ width: `${(activeVo.activeRegisteredNum /activeVo.activeLimit)*100}%` }"
                />
              </view>
              <text class="progress-text">已报名{{activeVo.activeRegisteredNum}}/{{activeVo.activeLimit}}人</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 底部占位 -->
      <view class="bottom-placeholder" />
    </scroll-view>
    <!-- 底部报名按钮 -->
    <view class="footer">
      <button class="signup-button" @click="handleSignup">立即报名</button>
    </view>
    <!-- 报名弹窗 -->
    <uni-popup ref="signupPopup" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">报名信息</text>
          <uni-icons
            class="cursor-pointer"
            type="close"
            size="24"
            color="#666666"
            @click="closePopup"
          />
        </view>
        <view class="form-content">
          <uni-forms ref="form" :model="formData" label-position="top">
			  
            <uni-forms-item v-for="i in activeVo.activeForm" :label="i.label" required>
				
              <uni-easyinput v-if="i.inputType === '0'" v-model="formData[i.name]" :placeholder="i.placeholder" />
			  
			        <uni-data-select v-if="i.inputType === '1'"
			        :localdata="i.optionValue"
			        v-model="formData[i.name]" :placeholder="i.placeholder">
			        </uni-data-select>
			  
              <bbm-select v-if="i.inputType === '2'" v-model="formData[i.name]" :data="i.optionValue" label_label="text" value_label="value" ></bbm-select>
			  
            </uni-forms-item>


          </uni-forms>
		  
          <button class="submit-button" @click="submitForm">确认提交</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>



<style scoped lang="scss">
.page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}
.header {
  position: relative;
  width: 750rpx;
  height: 500rpx;
  flex-shrink: 0;
}
.swiper {
  width: 100%;
  height: 100%;
}
.cover-image {
  width: 100%;
  height: 100%;
}
.cover-video {
  width: 100%;
  height: 100%;
}
.header-overlay {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 300rpx;
  background: linear-gradient(
    180deg,
    rgba(0, 0, 0, 0) 0%,
    rgba(0, 0, 0, 0.7) 100%
  );
}
.header-content {
  padding: 30rpx;
}
.header-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 100rpx;
}
.event-title {
  font-size: 36px;
  font-weight: bold;
  color: #ffffff;
}
.content {
  flex: 1;
  overflow: auto;
  padding: 30rpx;
  width: 92%;
}
.info-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}
.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}
.info-item:last-child {
  margin-bottom: 0;
}
.info-text {
  margin-left: 20rpx;
  font-size: 14px;
  color: #333333;
}
.tag-container {
  display: flex;
  margin-left: 20rpx;
  gap: 20rpx;
}
.tag {
  background: #f0f0f0;
  padding: 4rpx 16rpx;
  border-radius: 4rpx;
  font-size: 12px;
  color: #666666;
}
.price {
  margin-left: 20rpx;
  font-size: 20px;
  color: #ff4d4f;
  font-weight: bold;
}
.price-original {
  margin-left: 20rpx;
  font-size: 14px;
  color: #999999;
  text-decoration: line-through;
}
.section {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}
.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 30rpx;
}
.detail_video_img {
  .video_img-itme{
	.detail_video {
		width: 100%;
	}
	.detail_img {
		width: 100%;
	}
	width: 100%;
  }
  width: 100%;
  height: 500rpx;
}
.detail-content {
  color: #666666;
}
.detail-subtitle {
  display: block;
  font-size: 14px;
  font-weight: bold;
  margin: 20rpx 0;
}
.detail-text {
  font-size: 14px;
  line-height: 1.6;
}
.timeline {
  margin-top: 20rpx;
}
.timeline-item {
  display: flex;
  margin-bottom: 20rpx;
}
.time {
  min-width: 200rpx;
  font-size: 14px;
  white-space: nowrap;
  color: #999999;
  margin-right: 10rpx;
}
.event {
  flex: 1;
  font-size: 14px;
  color: #333333;
}
.people-info {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}
.organizer {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-bottom: 16rpx;
}
.name {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}
.role {
  font-size: 14px;
  color: #666666;
  margin-top: 8rpx;
}
.subtitle {
  display: block;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 16rpx;
}
.text {
  font-size: 14px;
  color: #666666;
}
.avatar-list {
  display: flex;
  margin-top: 20rpx;
  gap: 20rpx;
}
.guest-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
}
.signup-info {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}
.info-row {
  display: flex;
  align-items: center;
}
.label {
  width: 140rpx;
  font-size: 14px;
  color: #666666;
}
.value {
  flex: 1;
  font-size: 14px;
  color: #333333;
}
.progress-container {
  flex: 1;
}
.progress-bar {
  height: 16rpx;
  background: #f0f0f0;
  border-radius: 8rpx;
  overflow: hidden;
}
.progress {
  height: 100%;
  background: #1890ff;
}
.progress-text {
  font-size: 12px;
  color: #666666;
  margin-top: 8rpx;
}
.bottom-placeholder {
  height: 120rpx;
}
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 30rpx;
  background: #ffffff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.signup-button {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background: #1890ff;
  color: #ffffff;
  font-size: 16px;
  border-radius: 40rpx;
}
.popup-content {
  background: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  padding: 30rpx;
}
.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}
.popup-title {
  font-size: 16px;
  font-weight: bold;
  color: #333333;
}
.form-content {
  padding: 20rpx 0;
}
.submit-button {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background: #1890ff;
  color: #ffffff;
  font-size: 16px;
  border-radius: 40rpx;
  margin-top: 30rpx;
}
.cursor-pointer {
  cursor: pointer;
}
</style>
